package kassiopeia.agent.repository;

import java.io.File;
import javax.annotation.PostConstruct;
import kassiopeia.commons.exception.RepositoryException;
import kassiopeia.commons.model.Coordinates;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("pluginRepository")
public class RepositoryManager {

    private static final Logger logger = Logger.getLogger(RepositoryManager.class);

    @Value("${local.repository.url}")
    private String localRepositoryUrl;

    @Value("${remote.repository.url}")
    private String remoteRepositoryUrl;

    private Repository local;
    private Repository remote;

    @PostConstruct
    public void configure() {
        local = new LocalRepository(localRepositoryUrl);
        logger.info("Local plugin repository: " + local.getLocation());

        // TODO
        //remote = new MockRepository(remoteRepositoryUrl,localRepositoryUrl);
        remote = new MockRepository(remoteRepositoryUrl);
        logger.info("Remote plugin repository: " + remote.getLocation());
    }

    public synchronized File getPluginJar(Coordinates coords) {
        File pluginJar = searchLocalRepo(coords);
        if(pluginJar != null)
            return pluginJar;

        pluginJar = searchRemoteRepo(coords);
        if(pluginJar != null)
            return pluginJar;

        throw new RepositoryException("Can't find plugin " + coords + " in any repository");
    }

    public File searchLocalRepo(Coordinates coords) {
        logger.info("Searching for plugin: " + coords + " in local repository");
        File pluginJar = local.getPluginJar(coords);

        if(pluginJar != null) {
            logger.info("Plugin " + coords + " was found in local repository");
            return pluginJar;
        }
        logger.info("Plugin " + coords + " wasn't found in local repository.");
        return null;
    }

    public File searchRemoteRepo(Coordinates coords) {
        logger.info("Searching for plugin: " + coords + " in remote repository");
        File pluginJar = remote.getPluginJar(coords);

        if(pluginJar != null) {
            logger.info("Plugin " + coords + " was found in remote repository");
            return pluginJar;
        }
        logger.info("Plugin " + coords + " wasn't found in remote repository.");
        return null;
    }

    public String getLocalRepositoryUrl() {
        return localRepositoryUrl;
    }

    public String getRemoteRepositoryUrl() {
        return remoteRepositoryUrl;
    }
}
